package com.v5ba.server.config;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.v5ba.server.config.XATransactionConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @author yiren
 * @date 2018-08-23
 */
@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "db1EntityManager",//实体管理引用
        transactionManagerRef = "transactionManager",//事务管理引用
        basePackages = {"com.v5ba.server.repository.db1"}) //设置为目标JpaRepository所在包
public class DataSourceDB1Configurer {
    @Autowired
    private JpaVendorAdapter jpaVendorAdapter;

    //定义数据源
    @Bean(name = "db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db1")//application.yml文件内配置数据源的前缀
    public DataSource dataSource() {
        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        return xaDataSource;
    }

    //定义访问用户数据库的entityManager
    @Bean(name = "db1EntityManager")
    @DependsOn("transactionManager")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Throwable {

        HashMap<String, Object> properties = new HashMap<String, Object>();
        properties.put("hibernate.transaction.jta.platform", XATransactionConfig.AtomikosJtaPlatform.class.getName());
        properties.put("javax.persistence.transactionType", "JTA");
        properties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());
        properties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());

        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setJtaDataSource(dataSource());
        entityManager.setJpaVendorAdapter(jpaVendorAdapter);
        // 设置为该EntityManager所要管理的Entity类所在的包
        entityManager.setPackagesToScan("com.v5ba.server.entity.db1");
        entityManager.setPersistenceUnitName("db1PersistenceUnit");
        entityManager.setJpaPropertyMap(properties);

        return entityManager;
    }
}
